import { setUserAddress } from '../../services/user';
import { rawCitiesData } from './cityData'; // 导入城市数据

Page({
  data: {
    userName: '',
    userPhone: '',
    detail: '',
    selectValue: '', // 选择的值
    selectShow: false, // 是否显示级联组件
    regionData: '',
    addressInfo: 0,
    rawCitiesData, // mock的级联数据
    id: 0
  },
  onLoad(option) {
    my.setNavigationBar({
      title: option && option.addressInfo ? '修改地址' : '新增地址',
      backgroundColor: '#4BA3F9'
    })
    if (option.addressInfo) {
      let addressInfo = {}
      
      try {
        JSON.parse(option.addressInfo)
      } catch(error) {
        
      }

      this.setData({
        userName: addressInfo.name,
        userPhone: addressInfo.phone,
        detail: addressInfo.detail,
        id: addressInfo.id,
        addressInfo: addressInfo,
        selectValue: addressInfo.province + ' ' + addressInfo.city + ' ' + addressInfo.district,
      })

    }
  },
  onShow(option) {

  },
  inputname(e) {
    console.log(e)
    this.setData({
      userName: e.detail.value,
    });
  },
  inputphone(e) {
    this.setData({
      userPhone: e.detail.value,
    });
  },
  inputdetail(e) {
    this.setData({
      detail: e.detail.value,
    });
  },
  onSubmitAddress() {
    if (this.data.selectValue.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请选择收货地址',
        duration: 2000,
      });
      return
    }
    let provinceName = this.data.selectValue.split(' ')[0]
    let cityName = this.data.selectValue.split(' ')[1]
    let districtName = this.data.selectValue.split(' ')[2]
    
    if (this.data.userName.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请输入姓名',
        duration: 2000,
      });
      return
    }
    if (this.data.userPhone.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请输入电话',
        duration: 2000,
      });
      return
    }
    if (this.data.detail.length <= 0) {
      my.showToast({
        type: 'fail',
        content: '请输入您的详细地址',
        duration: 2000,
      });
      return
    }
    let param = {
      province: provinceName,
      city: cityName,
      district: districtName,
      detail: this.data.detail,
      phone: this.data.userPhone,
      name: this.data.userName,
      street: "",
    }
    if (this.data.id > 0) {
      param.userAddressId = this.data.id
    }
    setUserAddress(param).then(res => {
      if (res.code == "000000") {
        my.showToast({
          type: 'success',
          content: '保存成功',
          duration: 2000,
        });
        setTimeout(() => {
          my.navigateBack()
        }, 2000);
      }

    })
  },
  onReset() {
  },
  openSelect() {
    this.setData({ selectShow: true });
  },
  /**
   * 关闭级联组件
   * @method closeSelect
   */
  closeSelect() {
    this.setData({ selectShow: false });
  },
  /**
   * 点击确认触发的事件
   * @method onSelectSuccess
   * @param {*} result
   */
  onSelectSuccess(result) {
    let selectValue = '';
    result && result.forEach((item) => {
      selectValue += `${item.name} `;
    });
    
    if (selectValue.length > 0) {
      selectValue = selectValue.substr(0, selectValue.length - 1);
    }

    this.setData({ selectValue });
  },
  formatLocation(longitude, latitude) {
    longitude = Number(longitude).toFixed(2),
      latitude = Number(latitude).toFixed(2)

    return {
      longitude: longitude.toString().split('.'),
      latitude: latitude.toString().split('.')
    }
  },
  getLocation() {
    var that = this;
    my.getAddress({
      success: (res) => {
        let isSuccess = false
        if (res.resultStatus == '9000') {
          that.setData({ detail: res.result.address, userName: res.result.fullname, userPhone: res.result.mobilePhone })
          that.data.rawCitiesData.forEach(a => {
            if (a.name === res.result.prov) {
              a.sub.forEach(b => {
                if (b.name === res.result.city) {
                  b.sub.forEach(c => {
                    if (c.name === res.result.area) {
                      isSuccess = true;
                      that.setData({ selectValue: a.name + ' ' + b.name + ' ' + c.name });
                    }
                  })
                }
              })
            }
          });
        }
        if (!isSuccess) {
          my.showToast({
            type: 'fail ',
            content: '地址匹配失败，请手动选择',
            duration: 2000,
          });
        }
      }
    });
  },
});
